#!/usr/bin/perl

$TEMPLATE = $ARGV[0];
$DATA = $ARGV[1];
$OUTPUT = $ARGV[2];

$numFiles = $#ARGV + 1;

if ($numFiles < 2) {
    print "Not enough files specified.\n";
    exit -1;
}

$TEMPLATE = $ARGV[0];
@t = `cat "$TEMPLATE"`;

# 2 files specified
if ($numFiles == 2) {
    $OUTPUT = $ARGV[1];
    open(OUT, ">$OUTPUT");
    print OUT @t;
    close(OUT);
    exit 0;
} 

# 3 or more files specified
$OUTPUT = $ARGV[$numFiles-1];
open (OUT, ">$OUTPUT");
for ($i=1; $i<$numFiles-1; $i++) {
    $DATA = $ARGV[$i];
    $d = `cat "$DATA"`;
    $d =~ s/^\s*\/\*.*?\*\///s; # remove first /* ... */ comment
    $n = 0;
    foreach $line (@t) {
        if ($line =~ /#include\s+\"$DATA\"/) {
            $t[$n] = $d;# . "\n";
        }
	$n++;
    }
}

# substitute version number
$vers = `/usr/local/bin/svnversion -n .`;
($vers =~ m/\d+[MS]*$/) && ($ver = $&);
$ver = `cat version` . " (x" . $vers . ")";
$ver =~ s/[\r\n]//g;
$vers =~ s/[\r\n]//g;
$n = 0;
foreach $line (@t) {
    if ($line =~ /\$\(\(version\)\)/) {
        $line =~ s/\$\(\(version\)\)/$ver/;
        $t[$n] = $line;
    }
    if ($line =~ /\$\(\(ver\)\)/) {
        $line =~ s/\$\(\(ver\)\)/$vers/;
        $t[$n] = $line;
    }

    $n++;
}

print OUT @t;
close(OUT);
exit 0;
